<?php

class transaksi extends record {

    public function __construct() {
        parent::__construct();
    }

    function addDetailCart($idP, $jmlAsal,$autoAdd=false){
        $jml=($autoAdd==true)?$jmlAsal+1:$jmlAsal;
        //prepare cari data
        $this->namaTabel = 'v_produk';
        $this->get('id,nama,gambar,harga_modal,harga_jual,gambar,diskon,jumlah', array('id' => $idP), 1);
        $dtC = $this->execute();
        if ($dtC['success'] == true){
            if ($dtC['total'] > 0) {
                $result = $dtC['result'][0];
                $setSes = $result;
                if ($result['jumlah'] >= $jml) {
                    $setSes['jumlah_buy'] = $jml;                    
                    $hAkhir = $this->InsUpdCartItem($setSes,$autoAdd);
                } else {
                    $hAkhir = array('success' => false, 'error_msg' => 'Stok Tidak Cukup');
                }
            } else {
                $hAkhir = array('success' => false, 'error_msg' => 'Tidak Ada Produk Ini');
            }
        } else {
            $hAkhir = $dtC;
        };
        return $hAkhir;
    }
    function cekStok($key){
        $this->namaTabel = 'v_produk';
        $this->get('nama,jumlah', array('id'=>$key),1);
        $dt =  $this->execute();
        $sk = $dt['result'][0];
        $st= array('stok'=>isset($sk['jumlah'])?$sk['jumlah']:0,'nama'=>isset($sk['nama'])?$sk['nama']:'');
        return $st;
    }
    function InsUpdCartItem($arrSetSes = array(),$autoAdd=false){
        $cond = 'insert';
        if(isset($_SESSION['detail_cart']) && is_array($_SESSION['detail_cart'])){
            foreach ($_SESSION['detail_cart'] as $key => $value) {
                if($value['id']==$arrSetSes['id']){
                    $keyCh= $key;
                }
            };
            if(isset($keyCh)){                
                if($autoAdd==true){
                    $jmlAw = $_SESSION['detail_cart'][$keyCh]['jumlah_buy'];
                    $jmlAdd = $arrSetSes['jumlah_buy'];
                    unset($_SESSION['detail_cart'][$keyCh]['jumlah_buy']);
                    unset($arrSetSes['jumlah_buy']);
                    $arrSetSes['jumlah_buy'] = $jmlAw+$jmlAdd;
                }
                $_SESSION['detail_cart'][$keyCh]=$arrSetSes;
                $cond = 'update';
            }else{
                $_SESSION['detail_cart'][]=$arrSetSes;               
            }
        }
        else{
            $_SESSION['detail_cart'][]=$arrSetSes;
        }
        return array('success'=>true,'condition'=>$cond,'error_msg'=>' ');
    }
    function detailTemp(){
        $dt = isset($_SESSION['detail_cart']) ? $_SESSION['detail_cart'] : array();
        $c = count($dt);
       $r=array('total' => $c, 'result' => $dt);
       return $r;
    }

}

 $objTransaksi = new transaksi();